package com.dlc.apk.ui.fragment

import android.content.Context
import com.dlc.apk.App
import com.dlc.apk.R
import com.dlc.apk.api.ApiConstants
import com.dlc.apk.base.BaseApp
import com.dlc.apk.base.BaseFragment
import com.dlc.apk.databinding.FragmentWelcomeBinding
import com.dlc.apk.service.OnProcessListener
import com.dlc.apk.service.staff.IStaffService
import com.dlc.apk.service.staff.impl.StaffService
import com.dlc.apk.service.user.IUserService
import com.dlc.apk.service.user.impl.UserService
import com.dlc.apk.ui.activity.MainActivity
import com.dlc.apk.ui.model.AdForm
import com.dlc.apk.ui.model.AppForm
import com.dlc.apk.ui.view.AdPlayer
import com.dlc.apk.utils.CacheHelper
import com.dlc.apk.utils.DeviceUtil
import com.dlc.apk.utils.LogPlus
import com.jeremyliao.liveeventbus.LiveEventBus
import io.reactivex.disposables.Disposable


/**
 * @author We
 * @desc 欢迎页面
 */
class WelcomeFragment : BaseFragment() {
    private lateinit var adForm: AdForm
    private lateinit var appForm: AppForm
    private lateinit var userService: IUserService
    private lateinit var fragmentBinding: FragmentWelcomeBinding

    private lateinit var adPlayer: AdPlayer

    private lateinit var mStaffService: IStaffService

    override fun getLayoutId(): Int {
        return R.layout.fragment_welcome
    }

    override fun initViewModels() {
        adForm = AdForm()
        appForm = AppForm()

        appForm.versionName.set("v${DeviceUtil.packageVersion}")
    }

    override fun initServices() {
        userService = UserService()
        mStaffService = StaffService()
    }

    override fun init() {
        fragmentBinding = getViewDataBinding<FragmentWelcomeBinding>()!!
        fragmentBinding.adForm = adForm
        fragmentBinding.defaultAdUrl = AdPlayer.defaultAdUrl
        fragmentBinding.appForm = appForm

        val adItems = ArrayList<AdForm.AdItem>()
        adForm.adItems.set(adItems)
        fragmentBinding.ivDefaultAd.setOnClickListener {

        }

        fragmentBinding.rlWel.setOnClickListener {

        }

        fragmentBinding.vToTesting.setOnClickListener {
            (getParentActivity() as MainActivity).showLoginFragment(false)
        }

        //adPlayer
        initAdPlayer()
        //加载广告列表数据
        loadAdBannersData()
        //通知重新加载广告
        LiveEventBus.get(ApiConstants.EVENT_MQTT_UPDATE_ADVERT, String::class.java).observe(this, {
            loadAdBannersData()
        })
    }

    private var adDisplayDisposable: Disposable? = null

    private fun initAdPlayer() {
        adPlayer = AdPlayer(fragmentBinding.ivDefaultAd, fragmentBinding.vvDefaultAd)
        adPlayer.onAdPlayListener = object : AdPlayer.Companion.OnAdPlayListener {
            override fun onPlayed(adDataItem: AdPlayer.AdDataItem) {
                LogPlus.e("###广告播放次数+1,adId->${adDataItem.adId},总播放次数->${CacheHelper.getAdPlayTimes(adDataItem.adId)}")
                //记录该广告已播放总次数
                CacheHelper.saveAdPlayTimes(adDataItem.adId)
            }
        }
    }

    private fun loadAdBannersData() {
        adForm.onProcessListener = object : OnProcessListener<Any> {
            override fun onStart() {
                LogPlus.e("广告数据加载中...")
            }

            override fun onSuccess() {
                val adDataItems = ArrayList<AdPlayer.AdDataItem>()
                if (adForm.adItems.get()?.size != 0) {
                    //显示广告
                    fragmentBinding.defaultAdUrl = adForm.adItems.get()?.get(0)?.url
                    //适配数据
                    adForm.adItems.get()?.forEach {
                        val proxyUrl = (BaseApp.instance as App).getVideoCacheProxy().getProxyUrl(it.url)
                        val adDataItem = AdPlayer.AdDataItem(
                            if (it.type == AdForm.typeImage) AdPlayer.AdDataItem.AdType.IMAGE else AdPlayer.AdDataItem.AdType.VIDEO,
                            proxyUrl,
                            it.duration
                        )
                        adDataItem.startTime = it.startTime
                        adDataItem.endTime = it.endTime
                        adDataItem.startTimestamp = it.startTimestamp
                        adDataItem.endTimestamp = it.endTimestamp
                        adDataItem.adId = it.adId
                        adDataItem.playTimes = CacheHelper.getAdPlayTimes(it.adId)
                        adDataItems.add(adDataItem)
                    }
                    BaseApp.instance.runOnUiThread {
                        adPlayer.setDataSource(adDataItems)
                        adPlayer.restart()
                    }
                } else {
                    BaseApp.instance.runOnUiThread {
                        adPlayer.setDataSource(adDataItems)
                        adPlayer.showDefaultAd()
                    }
                }

            }

            override fun onFailure(extra: Any?, msg: String?) {
                showToast(msg)
            }

            override fun onComplete() {

            }
        }
        adForm.position = AdForm.AD_TYPE_FULLSCREEN
        userService.getAdBanners(adForm)
    }

    override fun onResume() {
        super.onResume()
        LogPlus.e("###onResume,fragment->" + this.javaClass.simpleName)

        //加载广告列表数据
        loadAdBannersData()
    }

    override fun onPause() {
        super.onPause()
        LogPlus.e("###onPause,fragment->" + this.javaClass.simpleName)
    }

    override fun onDetach() {
        super.onDetach()
        //adBanner?.pause(0)
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
    }

    override fun onDestroy() {
        super.onDestroy()
        adDisplayDisposable?.dispose()
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        LogPlus.e("###WelcomeFragment hidden->${hidden}")
        if (!hidden) {
            LogPlus.e("###广告显示")
            adPlayer.resume()
            //重新加载广告
            loadAdBannersData()
        } else {
            LogPlus.e("###广告隐藏")
            adPlayer.stop()
        }
    }
}